package cn.lcc.user.service.impl;

import cn.lcc.basic.exception.BusinessException;
import cn.lcc.basic.util.Md5Utils;
import cn.lcc.basic.util.StrUtils;
import cn.lcc.org.domain.Employee;
import cn.lcc.org.domain.Shop;
import cn.lcc.user.domain.Logininfo;
import cn.lcc.user.domain.User;
import cn.lcc.user.mapper.LogininfoMapper;
import cn.lcc.user.mapper.UserMapper;
import cn.lcc.user.service.IUserService;
import cn.lcc.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void save(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //创建Logininfo对象
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//1-用户
        logininfo.setDisable(true);

        //将Logininfo对象添加到数据库，并生成自增id
        logininfoMapper.save(logininfo);//自增长id

        //将logininfo_id设置到user对象中
        user.setLogininfoId(logininfo.getId());
        //添加到数据库
        super.save(user);
        //userMapper.save(user); //效果同上
    }
    @Override
    public void del(Long id) {
        //查询user对象
        User user = userMapper.loadById(id);
        //删除logininfo信息
        logininfoMapper.del(user.getLogininfoId());
        //删除user信息
        super.del(id);
    }


    @Override
    public void update(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //查询到原来的user对象
        User oldUser = userMapper.loadById(user.getId());
        user.setLogininfoId(oldUser.getLogininfoId());

        //更新数据t_user
        super.update(user);

        //更新数据t_logininfo
        Logininfo oldLogininfo = logininfoMapper.loadById(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        //属性同名原则会把员工的id拷贝给登录信息对象的id
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }
    @Override
    public void phoneRegister(Map<String, String> map) {
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");
        //一：校验 - 空值校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode) || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)) {
            throw new BusinessException("请填写相关数据");
        }
        //密码是否一致
        if (!password.equals(passwordRepeat)) {
            throw new BusinessException("密码不一致，请重新输入正确密码");
        }
        //三：校验 - 手机验证码是否过期，是否正确
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if (obj == null) {
            throw new BusinessException("手机验证码过期");
        }
        if (!obj.toString().split(":")[0].equals(phoneCode)) {
            throw new BusinessException("手机验证码错误");
        }
        //四：添加到数据库，密码加密加盐
        User user = map2User(phone, password);
        Logininfo logininfo = user2Logininfo(user);
        //1.先添加t_logininfo
        logininfoMapper.save(logininfo);//添加之后会生成自增长id
        //2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    @Override
    public void emailRegister(Map<String, String> map) throws MessagingException {
        String email = map.get("email");
        String password = map.get("emailpassword");
        String emailpasswordRepeat = map.get("emailpasswordRepeat");
        //一：校验 - 空值校验
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password) || StringUtils.isEmpty(emailpasswordRepeat)) {
            throw new BusinessException("请填写相关数据");
        }
        User user = userMapper.loadByEmail(email);
        if(user != null){
            throw new BusinessException("该邮箱已注册，请直接登录。忘记密码请联系管理员");
        }
        //密码是否一致
        if (!password.equals(emailpasswordRepeat)) {
            throw new BusinessException("密码不一致，请重新输入正确密码");
        }
        //四：添加到数据库，密码加密加盐
        User user2 = map2User2(email, password);
        Logininfo logininfo2 = user2Logininfo2(user2);
        //1.先添加t_logininfo
        logininfoMapper.save(logininfo2);//添加之后会生成自增长id
        //2.再添加t_user
        user2.setLogininfoId(logininfo2.getId());
        userMapper.save(user2);
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("694652657@qq.com ");
        helper.setSubject("注册激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
       /* Shop shop = shopMapper.loadById(log.getShopId());*/

       /* helper.setText("<h1>你的店铺已经注册!!!</h1><img src='http://123.207.27.208"+shop.getLogo()
                        +"' ><a href='http://127.0.0.1:8080/shop/active/"+shop.getId()+"'>点击该链接激活</a>",
                true);*/
        helper.setText("<h1>注册激活!!!</h1><a href='http://127.0.0.1:8080/user/active/"+user2.getId()+"'>点击该链接激活</a>",true);
        /*Employee employee = employeeMapper.loadById(shop.getAdminId());*/
        //收件人
        helper.setTo(user2.getEmail());
        javaMailSender.send(mimeMessage);
    }

    @Override
    public void active(Long id) {
        User user = userMapper.loadById(id);
        user.setState(1);
        userMapper.update(user);
    }

    private User map2User2(String email, String password) {
        User user = new User();
        user.setUsername(email);
        user.setEmail(email);
        //对密码和盐值进行处理
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(password + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(0);
        return user;
    }

    private Logininfo user2Logininfo2(User user2) {
        Logininfo logininfo = new Logininfo();
        //底层会按照属性同名原则进行属性的拷贝：id,username,phone,email,salt,password
        BeanUtils.copyProperties(user2, logininfo);
        logininfo.setType(1);//1表示用户
        logininfo.setDisable(true);
        return logininfo;
    }


    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //底层会按照属性同名原则进行属性的拷贝：id,username,phone,email,salt,password
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);//1表示用户
        logininfo.setDisable(true);
        return logininfo;
    }

    private User map2User(String phone, String password) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        //对密码和盐值进行处理
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(password + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }
}
